package io.gitee.chearnee.fw.openapi.result;

import io.gitee.chearnee.fw.openapi.constant.enums.ResultCode;
import io.gitee.chearnee.fw.openapi.exception.OpenApiException;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2021/9/18 11:31
 */
@Getter
@Setter
@NoArgsConstructor
public class OpenApiResult<T> {

  private int code;
  private String msg;
  private T data;

  private OpenApiResult(ResultCode resultCode, T data, String message) {
    this.code = resultCode.getValue();
    this.msg = message;
    this.data = data;
  }

  private OpenApiResult(ResultCode resultCode, T data) {
    this(resultCode, data, null);
  }

  public static <T> OpenApiResult<T> success(T data) {
    return new OpenApiResult<>(ResultCode.SUCCESS, data);
  }

  public static <T> OpenApiResult<T> fail(String message) {
    return new OpenApiResult<>(ResultCode.FAILED, null, message);
  }

  public static <T> OpenApiResult<T> fail(OpenApiException openApiException) {
    return fail(openApiException.getResultCode(), openApiException.getMessage());
  }

  public static <T> OpenApiResult<T> fail(ResultCode resultCode) {
    return fail(resultCode, resultCode.getDesc());
  }

  public static <T> OpenApiResult<T> fail(ResultCode resultCode, String message) {
    return new OpenApiResult<>(resultCode, null, message);
  }

  public boolean getSuccess() {
    return code == ResultCode.SUCCESS.getValue();
  }
}
